package com.cjl.interview150.stack;

import org.junit.jupiter.api.Test;

import java.awt.*;
import java.util.*;

public class StackPractice {
    /**
     * 71. 简化路径
     *
     * @param path
     * @return
     */
    public String simplifyPath(String path) {
        // 定义栈收集路径名称
        ArrayDeque<String> stack = new ArrayDeque<>();
        // 以"/"分割路径
        String[] names = path.split("/");
        for (String name : names) {
            if ("..".equals(name)) { // 如果是..则退回上一级路径
                if (!stack.isEmpty()) { // 注意这两个条件不可以合并着写,因为如果合并写则..会在下方的elseif入栈
                    stack.pollLast();
                }
            } else if (name.length() > 0 && !".".equals(name)) { // 如果长度大于1并且不是.则是有效目录名称
                stack.offerLast(name);
            }
        }
        StringBuilder sb = new StringBuilder();
        // 如果栈为空则直接添加根路径
        if (stack.isEmpty()) {
            sb.append("/");
        }
        // 只要栈不为空则不断取出目录名拼接
        while (!stack.isEmpty()) {
            sb.append("/");
            sb.append(stack.pollFirst());
        }
        return sb.toString();
    }

    /**
     * 224. 基本计算器
     * @param s
     * @return
     */
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        int len = s.length();
        int sign = 1;
        int i = 0;
        int res = 0;
        while (i < len) {
            switch (s.charAt(i)) {
                case ' ':
                    i++;
                    break;
                case '+':
                    sign = stack.peek();
                    i++;
                    break;
                case '-':
                    sign = -stack.peek();
                    i++;
                    break;
                case '(':
                    stack.push(sign);
                    i++;
                    break;
                case ')':
                    stack.pop();
                    i++;
                    break;
                default:
                    long num = 0;
                    while (i < len && Character.isDigit(s.charAt(i))) {
                        num = num * 10 + (s.charAt(i) - '0');
                        i++;
                    }
                    res += sign * num;
            }
        }
        return res;
    }


}

/**
 * 155. 最小栈
 */
class MinStack {

    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
        minStack.push(Integer.MAX_VALUE);
    }

    public void push(int val) {
        stack.push(val);
        minStack.push(Math.min(val, minStack.peek()));
    }

    public void pop() {
        stack.pop();
        minStack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}
